##################################

# APPENDIX FIGURE 7: SPATIAL COMPETITION EXERCISE

#################################

rm(list = ls())

# set choice set two radii to compare
r = c(550,800)

# create storage vectors
intersection_vector=matrix(data=0, nrow=100,ncol=2)
x_axis=1:100
x_axis=x_axis*10

# compute probability that building is competitor at distances from 0 to 1000
# we loop over distance (k index) and choice set radius (k index)
for (k in 1:100){
  
  for (j in 1:2){
    
    # set radii and distance, compute choice set area
    d = k*10
    r1=r[j]
    r2=r[j]
    
    a1=pi*r1^2
    a2=pi*r2^2
    
    # this formula gives the area of overlap between two circles with radii r1 and r2 that 
    d1 = (r1^2-r2^2+d^2)/(2*d)
    d2 = d - d1
    intersection=r1^2*acos(d1/r1) - d1*(r1^2-d1^2)^(1/2) + r2^2*acos(d2/r2) - d2*(r2^2-d2^2)^(1/2) 
    
    # the probability of being a competitor is just the intersection divided by the area of the choice set
    prob_competitor=intersection/a2
    intersection_vector[k,j]=prob_competitor
  
  }
  
}

# plot
# dev.off()
plot(x_axis,intersection_vector[,1],type="l",col="red",ylab="P(New Building Is Competitor)", xlab="Distance to New Building")
lines(x_axis,intersection_vector[,2],col="blue",type="b")
legend(0,.2, legend=c("550m Choice Set Radius", "800m Choice Set Radius"),
       col=c("red", "blue"), lty=1:2, cex=0.8,box.lty=0)

# list probabilities cited in text
intersection_vector[20,]
intersection_vector[50,]